package forword;

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.io.IOUtils;
import org.apache.commons.lang.StringUtils;

@WebFilter("/*")
public class ProxyFilter implements Filter {

	public ProxyFilter() {
	}

	public void destroy() {
	}

	public void doFilter(ServletRequest request1, ServletResponse response1, FilterChain chain1) throws IOException, ServletException {
		HttpServletRequest request = (HttpServletRequest) request1;
		HttpServletResponse response = (HttpServletResponse) response1;
		request.setCharacterEncoding("UTF-8");
		response.setCharacterEncoding("UTF-8");

		String basePath = request.getScheme() + "://" + "127.0.0.1:9080";
		String locationUrl = basePath + request.getRequestURI();
		String queryValue = request.getQueryString();
		if (StringUtils.isNotBlank(queryValue)) {
			locationUrl += "?" + queryValue;
		}
		IOUtils.write(HttpUtils.sendGet(locationUrl, request), response.getOutputStream());
	}

	public void init(FilterConfig fConfig) throws ServletException {
	}

	@SuppressWarnings("unused")
	private String solveUrl(HttpServletRequest request) {
		return request.getRequestURI().replaceAll(request.getContextPath(), "");
	}

	public static void main(String[] args) {
	}

}
